package cn.elricyu.kf.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.validation.FieldError;
import org.springframework.web.servlet.View;

public class JsonView implements View {
	@Autowired
	private MessageSource messageSource;

	public String getContentType() {
		return "application/json";
	}

	public void render(Map model, HttpServletRequest request,
			HttpServletResponse response) {
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			response.setContentType("text/plain; charset=UTF-8");
			JSONObject jsonObject = new JSONObject();
			for (Object object : model.entrySet()) {

				if (object instanceof FieldError) {
					FieldError fieldError = (FieldError) object;

					jsonObject.put(fieldError.getField(), messageSource
							.getMessage(fieldError, null));
				}
			}
			writer.print(jsonObject.toString());

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}

}
